package com.huluobo.base.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType

/**
 *  Created by LC on 2024/12/25.
 */
abstract class BaseFragment<VDB : ViewDataBinding, VM : BaseViewModel> : Fragment() {
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val binding: VDB by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null, layoutInflater) as VDB
    }

    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(requireActivity())[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.e("TagA", "onError:${t.message}")
        t.printStackTrace()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        vm.onFailed.observe(requireActivity(), ::onError)
        initView()
        initData()
    }

    abstract fun initData()

    abstract fun initView()
}